<?php
/**
 * @author Mingming Tang iamalazyrat@gmail.com
 */

class Product_Controller extends Base_Controller {

  public $restful = true;

  public function get_index() {
    return Redirect::to(url('product/list'));
  }

  /**
   * 已选商品列表
   */
  public function get_list() {
    $page_size = 40;
    $page = Input::get('p', 1);
    //获得选取商品的分类
    $category_id = Input::get('category_id', false);
    $category = Category::find($category_id);
    //活的商品的Tag
    $tag_str = Input::get('tag', false);
    $tag = Tag::where('name', '=', $tag_str);
    if ($category) $tag->where('category_id', '=', $category->id);
    $tag = $tag->first();


    $products = Product::with('tags')->take($page_size)->order_by('id', 'desc');
    if ($category) {
      $cate_product_id = DB::table('category_product')->where('category_id', '=', $category->id)->get();
      $id = array(0);
      foreach ($cate_product_id as $v) $id[] = $v->product_id;
      if ($id) $products->where_in('id', $id);
    }

    if ($tag) {
      $tag_product_id = DB::table('product_tag')->where('tag_id', '=', $tag->id)->get();
      $id = array(0);
      foreach ($tag_product_id as $v) $id[] = $v->product_id;
      if ($id) $products->where_in('id', $id);
    }
    $count = $products->count();
    $products = $products->skip(($page - 1)*$page_size)->get();
    $url = url('product/list') . "?category_id={$category_id}&tag={$tag_str}";
    $page = Pagination::page($page, $count, $page_size, $url);
    return View::make('product.list.main')->with('products', $products)->with('page', $page);
  }

  /**
   * 商品编辑页面
   */
  public function get_edit() {
    $product = Product::find(Input::get('product_id', false));
    return View::make('product.edit.main')->with('product', $product);
  }

  /**
   * 商品手动添加页面
   */
  public function get_add() {
    return View::make('product.add.main');
  }

  /**
   * 删除已选商品
   */
  public function post_delete() {
    $product = Product::find(Input::get('product_id', false));
    if ($product) $product->delete();
    return Response::json(array('code'=>200, 'msg'=>'操作成功'));
  }


  /**
   * 淘宝商品挑选页面
   */
  public function get_taobao() {
    $keyword = Input::get('keyword', false);
    $cid = Input::get('cid', false);
    $sort= Input::get('sort', 'default');
    $start_coupon_rate = Input::get('start_coupon_rate', 0);
    $end_coupon_rate = Input::get('end_coupon_rate', 100);
    $page = Input::get('p', 1);
    $page_size = 40;
    $products = array();
    if ($cid OR $keyword) {
      $c = new TopClient;
      $c->appkey = Config::get('app.appkey');
      $c->secretKey = Config::get('app.secret');
      $req = new TaobaokeItemsCouponGetRequest;
      $req->setKeyword($keyword);
      $req->setCouponType($page);
      $req->setCid($cid);
      $req->setShopType("all");
      $req->setSort($sort);
      $field = array('num_iid', 'seller_id', 'nick', 'title', 'price', 'item_location', 'seller_credit_score', 'click_url', 'shop_click_url', 'pic_url', 'taobaoke_cat_click_url', 'keyword_click_url', 'coupon_rate', 'coupon_price', 'coupon_start_time', 'coupon_end_time', 'commission_rate', 'commission', 'commission_num', 'commission_volume', 'volume', 'shop_type');
      $req->setFields(implode(',', $field));
      $req->setStartCouponRate($start_coupon_rate * 100);
      $req->setEndCouponRate($end_coupon_rate * 100);
      $req->setPageNo($page);
      $req->setPageSize($page_size);
      $resp = $c->execute($req);
      $products = $resp->taobaoke_items;
    } 
    $url = url('product/taobao') . "?cid={$cid}&sort={$sort}&keyword={$keyword}&start_coupon_rate={$start_coupon_rate}&end_coupon_rate={$end_coupon_rate}";
    $page = Pagination::page($page, $page_size*100, $page_size, $url);
    return View::make('product.taobao.main')->with('products', $products)->with('page', $page);
  }


  /**
   * 淘宝商品分类更新，存入本地数据库
   */
  public function get_update_taobao_categories() {
    $c = new TopClient;
    $c->appkey = Config::get('app.appkey');
    $c->secretKey = Config::get('app.secret');
    $req = new ItemcatsGetRequest;
    $req->setFields("cid,parent_cid,name,is_parent, status");
    $req->setParentCid(0);
    $resp = $c->execute($req);
    $categories = $resp->item_cats;
    $cates = array();
    foreach ($categories->item_cat as $c) {
      $cate = Tcate::where('cid', '=', $c->cid)->first();
      if (!$cate) {
        $cate = Tcate::create(array('cid'=>$c->cid, 'name'=>$c->name));
      } else {
        $cate->name = $c->name;
        $cate->save();
      }
      $cates[] = $cate;
    }
    return Response::json(array('code'=>200, 'cates'=>$cates));
  }


  /**
   * 商品分类列表
   */
  public function get_category() {
    return View::make('product.category.main');
  }

  /**
   * 添加商品分类
   */
  public function post_category() {
    $input = Input::all();
    $rules = array(
      'cname' => 'required|max:50|unique:categories,cname',
      'ename' => 'max:50',
    ); 
    $messages = array(
      'cname_required' => '您没有填写中文类型名称',
      'cname_unique' => '您填写中文类型名称已经有了',
      'cname_max' => '您填写的中文类型名称太长了',
      'ename_max' => '您填写的英文类型名称太长了',
    );
    $validation = Validator::make($input, $rules, $messages);
    if ($validation->fails()) {
      $ret = array('code'=>400, 'msg' => $validation->errors->all());
    } else {
      Category::create($input);
      $ret = array('code'=>200, 'msg' => '操作成功');
    }
    return Response::json($ret);
  }

  /**
   * 编辑商品分类
   */
  public function post_category_edit() {
    $input = Input::all();
    $rules = array(
      'cname' => 'required|max:50|unique:categories,cname,' . $input['id'],
      'ename' => 'max:50',
    ); 
    $messages = array(
      'cname_required' => '您没有填写中文类型名称',
      'cname_unique' => '您填写中文类型名称已经有了',
      'cname_max' => '您填写的中文类型名称太长了',
      'ename_max' => '您填写的英文类型名称太长了',
    );
    $validation = Validator::make($input, $rules, $messages);
    if ($validation->fails()) {
      $ret = array('code'=>400, 'msg' => $validation->errors->first());
    } else {
      $category = Category::find($input['id']);
      if ($category) {
        $category->fill($input);
      }
      $category->save();
      $ret = array('code'=>200, 'msg' => '操作成功');
    }
    return Response::json($ret);
  }

  /**
   * 删除商品分类
   */
  public function post_delete_category() {
    $input = Input::all();
    if (!isset($input['id'])) return Response::json(array('code'=>400, 'msg'=> '参数错误'));
    $category = Category::find($input['id']);
    if (!$category) return Response::json(array('code'=>400, 'msg'=> '找不到'));
    $category->delete();
    return Response::json(array('code'=>200, 'msg'=> '操作成功'));
  }

  
  /**
   * 选取淘宝商品操作
   */
  public function post_add_taobao_product() {
    //获得选取商品的分类
    $category = Category::find(Input::get('category_id', false));
    if (!$category) return Response::json(array('code'=>400, 'msg'=>'您没有选择商品类型或类型不存在'));

    //获得选取商品的标签
    $tag_str = trim(Input::get('tag', '其它'));
    $tags = mb_split('\s|,|，', $tag_str);
    $tag_array = array();
    foreach ($tags as $t) {
      if (trim($t) == '') continue;
      $tag = Tag::where('category_id', '=', $category->id)->where('name', '=', $t)->first();
      if (!$tag) $tag = Tag::create(array('category_id' => $category->id, 'name' => $t));
      $tag_array[] = $tag;
    }

    // 处理选取的商品数据
    $product = Input::get('product', array());
    if (!$product) return Response::json(array('code'=>400, 'msg'=>'您没有选择商品'));
    $rules = array(
      'title' => 'required|max:1024',
      'url' => 'required|max:1024',
      'pic_url' => 'required|max:1024',
      'price' => 'required',
      'coupon_rate' => 'required',
      'coupon_price' => 'required',
      'coupon_start_time' => 'required',
      'coupon_end_time' => 'required',
      'mall' => 'required',
    );

    //插入数据 关联标签
    foreach ($product as $p) {
      $validation = Validator::make($p, $rules);
      if ($validation->fails()) continue;

      $item = Product::where('title', '=', $p['title'])->first(); 
      if (!$item) $item = Product::create($p);
      DB::table('category_product')->where('category_id', '=', $category->id)->where('product_id', '=', $item->id)->delete();
      DB::table('category_product')->insert(array('category_id'=>$category->id, 'product_id'=>$item->id));
      foreach ($tag_array as $tag) {
        DB::table('product_tag')->where('product_id', '=', $item->id)->where('tag_id', '=', $tag->id)->delete();
        DB::table('product_tag')->insert(array('product_id'=>$item->id, 'tag_id'=>$tag->id));
      }
    }
    return Response::json(array('code'=>200, 'msg'=>'操作成功'));
  }

  /**
   * 删除淘宝商品操作
   */
  public function post_remove_taobao_product() {
    // 获得商品
    $product = Input::get('product', array());
    if (!$product) return Response::json(array('code'=>400, 'msg'=>'您没有选择商品'));

    //删除关联数据
    foreach ($product as $p) {
      $item = Product::where('title', '=', $p['title'])->first(); 
      if ($item) {
        DB::table('category_product')->where('product_id', '=', $item->id)->delete();
        DB::table('product_tag')->where('product_id', '=', $item->id)->delete();
        $item->delete();
      }
    }
    return Response::json(array('code'=>200, 'msg'=>'操作成功'));
  }



  /**
   * 设置自动添加条件
   */
  public function post_set_auto() {
    //获得选取商品的分类
    $category = Category::find(Input::get('category_id', false));
    if (!$category) return Response::json(array('code'=>400, 'msg'=>'您没有选择商品类型或类型不存在'));

    $mall_str = trim(Input::get('mall', '其它'));
    $tag_str = trim(Input::get('tag', '其它'));
    $detail_str = trim(Input::get('detail', '其它'));
    Auto::where('mall', '=', $mall_str)->where('category_id', '=', $category->id)->where('tag', '=', $tag_str)->where('detail', '=', $detail_str)->delete();
    Auto::create(array('mall'=> $mall_str, 'category_id'=>$category->id, 'tag'=>$tag_str, 'detail'=>$detail_str));
    return Response::json(array('code'=>200, 'msg'=>'操作成功'));
  }

  public function get_auto() {
    $page = Input::get('p', 1);
    $page_size = 20;
    $start = ($page - 1) * $page_size;

    $category_id = Input::get('category_id', false);
    $category = Category::find($category_id);
    $mall = Input::get('mall', false);
    
    $autos = Auto::take($page_size)->skip($start);
    if ($category) $autos->where('category_id', '=', $category->id);
    if ($mall) $autos->where('mall', '=', $mall);
    $auto_item = $autos->order_by('id', 'desc')->get();
    $url = url('product/auto') . "?category_id={$category_id}&mall={$mall}";
    $page = Pagination::page($page, $autos->count(), $page_size, $url);
    return View::make('product.auto.main')->with('autos', $auto_item)->with('page', $page);
  }

  public function post_delete_auto() {
    $auto_id = Input::get('auto_id', false);
    $auto = Auto::find($auto_id);
    if ($auto) $auto->delete();
    return Response::json(array('code'=>200, 'msg'=>'操作成功'));
  }

}
